package com.qianyu.project.core.service.impl;

import com.qianyu.project.core.bean.FlowNode;
import com.qianyu.project.core.mapper.FlowNodeMapper;
import com.qianyu.project.core.service.IFlowNodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.validation.constraints.NotNull;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

/**
 * @author gs
 * @date create in 2020/12/11 16:07
 */
@Service
@Transactional(rollbackFor = Exception.class)
@Validated
public class FlowNodeServiceImpl implements IFlowNodeService {

    @Autowired
    private FlowNodeMapper flowNodeMapper;

    @Override
    public FlowNode renderFirtstNode (@NotNull Integer flowId) {
        return flowNodeMapper.selectFirtstNode(flowId);
    }

    @Override
    public FlowNode renderNextNode(FlowNode flowNode) {
        return flowNodeMapper.selectNextNode(flowNode);
    }

    @Override
    public FlowNode getById(@NotNull Integer flowNodeId) {
        return flowNodeMapper.selectById(flowNodeId);
    }

    @Override
    public String getTargetValue(Map<String,String> params) {
        return flowNodeMapper.selectTargetValue(params);
    }

    @Override
    public List<FlowNode> getListByFlowId(Integer flowId) {
        List<FlowNode> list = flowNodeMapper.getListByFlowId(flowId);
        Collections.sort(list, new Comparator<FlowNode>() {
            @Override
            public int compare(FlowNode o1, FlowNode o2) {
                if(o1.getSeq() > o2.getSeq())
                {
                    return 1;
                }
                else if(o1.getSeq() .equals( o2.getSeq()))
                {
                    return 0;
                }
                else
                {
                    return -1;
                }
            }
        });
        return list;
    }

    @Override
    public void saveBatch(List<FlowNode> nodeList) {
        flowNodeMapper.saveBatch(nodeList);
    }

    @Override
    public void update(Integer flowId) {
        flowNodeMapper.updateBatch(flowId);
    }

    @Override
    public void delete(Integer flowId) {
        flowNodeMapper.delete(flowId);
    }
}
